import React, { useEffect, useRef } from 'react';
import { useCustomState } from '@/hooks/useEffect';
import {
    PlusOutlined,
    CarryOutOutlined,
    DownOutlined,
    RightOutlined
} from '@ant-design/icons';
import AddDepartDialog from './add'
import {
    Button,
    Input,
    Card,
    message,
    Popconfirm,
    // Modal
} from 'antd';
import { YzhProgressDialog, YzhSkeleton, YzhTable } from '@com'
import ProTable, {
    // ProColumns,
    // ActionType,
    // TableDropdown
} from '@ant-design/pro-table';
import api from '@/api/apiList'
import { arrayToTree, findParentNodes } from '@/utils'
import {
    hasPermission,
    permissionCodes as pCodes
} from '@/routes/permission'
// const { confirm } = Modal;
import { antConfig } from '@/config'
const DepartManage = (props) => {
    const actionRef = useRef();
    const progressDialogRef = useRef(null);
    const { showTabsBar, showFooter } = props.themeConfig
    let clientHeight = document.body.clientHeight
    const [scroll, setScroll] = useCustomState(props.scroll || { x: 1500, y: clientHeight });
    const [state, setState] = useCustomState({
        deptId: '',
        loaded: false,
        dialogAddVisible: false,
        treeData: [],
        defaultExpandedKeys: ['0'],
        form: {
            deptName: '',
            pid: '',
            deptErpCode: '',
        },
        arrayToTree: arrayToTree
    });
    const columns = [
        {
            title: '部门名称',
            dataIndex: 'name',
            hideInSearch: true,
            // copyable: true,
            // align: 'center',
            width: 480,
            renderFormItem: (_, { type, defaultRender, formItemProps, fieldProps, ...rest }, form) => {
                if (type === 'form') {
                    return null;
                }
                return (
                    // value 和 onchange 会通过 form 自动注入。
                    <Input
                        // 组件的配置
                        {...fieldProps}
                        // 自定义配置
                        key="name"
                        placeholder="请输入部门名称"
                    />
                );
            },
            formItemProps: {
                rules: [
                    {
                        required: false,
                        message: '此项为必填项',
                    },
                ],
            },
        },
        {
            title: '部门绑定人数',
            dataIndex: 'num',
            hideInSearch: true,
            align: 'center',
            // sorter: true,
            width: 250
        },
        {
            title: '排序',
            dataIndex: 'sort',
            // sorter: true,
            fixed: 'right',
            hideInSearch: true,
            align: 'center',
            order: 2,
            width: 250,
            render: (text, record, index, action) => {
                // console.log(text, record, index, '12312');
                return hasPermission([pCodes.dept.sort]) && [
                    <Button
                        disabled={record.index === 0}
                        type="link"
                        key="move-up"
                        onClick={() => onMove('up', record, action)}>
                        上移
                    </Button>,
                    <Button type="link"
                        disabled={record.pIndex === record.index}
                        onClick={() => onMove('down', record, action)}
                        key="move-down">
                        下移
                    </Button>,
                ]
            },
        },
        {
            title: '操作',
            valueType: 'option',
            align: 'center',
            fixed: 'right',
            width: 180,
            render: (text, record, _, action) => [
                (hasPermission([pCodes.dept.edit]) && <a type={'text'}
                    key="editable"
                    disabled={record.id === '0'}
                    onClick={() => onEdit(record)}>
                    修改
                </a>),
                (hasPermission([pCodes.dept.remove]) && <Popconfirm
                    key="delete"
                    placement="topRight"
                    title={<p key="desc" style={{ maxWidth: 200 }}>是否确认删除该部门？</p>}
                    onConfirm={() => onDelete(record, action)}
                >
                    <a type={'text'} disabled={record.id === '0'} key="delete">
                        删除
                    </a>
                </Popconfirm>)
            ],
        },
    ];
    // 修改
    const onEdit = async (row) => {
        try {
            let res = await api.userCenter.department.info({ id: row.id })
            let data = res.result
            setState({
                ...state,
                dialogAddVisible: true,
                form: {
                    deptName: data.name || row.name,
                    pid: data.pid || row.pid,
                    id: data.id || row.id,
                    deptErpCode: data.saleErpCode || row.saleErpCode,
                }
            })
        } catch (error) {
            console.log(error);
        }
    }
    const onSubmit = async (values) => {
        if (values) {
            setState({
                ...state,
                dialogAddVisible: false
            })
            let params = {
                "deptErpCode": values.deptErpCode,
                "name": values.deptName,
                "pid": values.pid
            }
            let res = ''
            if (state.form.id) {
                params.id = state.form.id
                res = await api.userCenter.department.edit({ ...params })
            } else {
                res = await api.userCenter.department.add({ ...params })
            }
            res && res.success && message.success(res.message || '操作成功')
            res && !res.success && message.error(res.message || '操作失败')
            actionRef.current.reload()
            // getTableData()
            return
        }
        setState({
            ...state,
            dialogAddVisible: false
        })
    }
    // 排序
    const onMove = async (type, record, action) => {
        let parentNode = findParentNodes(state.treeData, record.pid) || []
        parentNode = (parentNode.length && parentNode[parentNode.length - 1]) || ''
        // console.log(parentNode, record, 'findParentNodes');
        let params = {
            "firstId": record.id,
            "firstOriginSortValue": record.sort,
            "secondId": 0,
            "secondOriginSortValue": 1
        }
        if (parentNode && parentNode.nodes && parentNode.nodes.length) { // 子级移动
            parentNode.nodes && parentNode.nodes.length && parentNode.nodes.map((el, index) => {
                if (record.id === el.id) {
                    let nextIndex = type === 'up' ? index - 1 : index + 1
                    if (parentNode.nodes[nextIndex]) {
                        params.secondId = parentNode.nodes[nextIndex].id
                        params.secondOriginSortValue = parentNode.nodes[nextIndex].sort || 1
                    }
                }
                return el
            })
        } else {
            state.treeData.map((el, index) => { // 顶级移动
                if (record.id === el.id) {
                    let nextIndex = type === 'up' ? index - 1 : index + 1
                    if (state.treeData[nextIndex]) {
                        params.secondId = state.treeData[nextIndex].id
                        params.secondOriginSortValue = state.treeData[nextIndex].sort || 1
                    }
                }
                return el
            })
        }
        // console.log(params, 'action');
        let res = await api.userCenter.department.sort({ ...params })
        res && res.success && message.success(res.message || '操作成功')
        action.reload()
        // getTableData()
    }
    // 删除
    const onDelete = async (record, action) => {
        let res = await api.userCenter.department.remove({ id: record.id })
        res && res.success && message.success(res.message || '操作成功')
        action.reload()
        // getTableData()
    }
    // 设置树结构索引
    const getTableData = async (params, sort, filter) => {
        // console.log(params, sort, filter);
        let res = await api.userCenter.department.tree({})
        if (!res || res.result === null) {
            return { data: [], msg: res && res.message, success: true }
        }
        let treeData = res.result
        // treeData = arrayToTree(treeData)
        const getExpandedKeys = (tree, newExpandedKeys) => { // 获取到所有可展开的父节点
            tree.map((item, index) => {
                if (item.nodes) {
                    newExpandedKeys.push(item.id)
                    getExpandedKeys(item.nodes, newExpandedKeys)
                }
                item.pIndex = tree.length - 1
                item.index = index
                item.icon = <CarryOutOutlined />
                return item
            })
            return { newExpandedKeys, tree }
        }
        let newExpandedKeys = getExpandedKeys(treeData, []).newExpandedKeys
        treeData = getExpandedKeys(treeData, []).tree
        setState({
            treeData,
            loaded: true,
            defaultExpandedKeys: [...newExpandedKeys]
        })
        return { data: treeData, msg: res.message, success: true }
    }
    useEffect(() => {
        setScroll(props.scroll)
        !state.loaded && getTableData()
    }, [props.scroll, state])


    const onAdd = () => {
        setState({
            ...state,
            form: {
                deptName: '',
                pid: '',
                deptErpCode: ''
            },
            dialogAddVisible: true
        })
    }
    const scrollY = scroll.y - (hasPermission([pCodes.dept.add]) ? 280 : 240)
    return (
        <Card className="user-manage" bordered={false} bodyStyle={{ padding: '0 0 20px' }}>
            {state.loaded ? <YzhTable
                {...antConfig.tableConfig}
                tableStyle={{ paddingTop: !hasPermission([pCodes.dept.add]) && 20 }}
                params={{ deptId: state.deptId }}
                columns={columns}
                scroll={{
                    x: 1000,
                    y: scrollY
                }}
                rowSelection={false}
                actionRef={actionRef}
                dataSource={state.treeData}
                request={async (params = {}, sort, filter) => getTableData(params, sort, filter)}
                rowKey="id"
                search={false}
                expandable={{
                    childrenColumnName: 'nodes',
                    // defaultExpandedRowKeys: [...state.defaultExpandedKeys],
                    indentSize: 30,
                    defaultExpandAllRows: true,
                    expandIcon: ({ expanded, onExpand, record }) =>
                    (record.nodes && record.nodes.length ? expanded ? (
                        record.nodes && <DownOutlined style={{ marginRight: 10 }} onClick={e => onExpand(record, e)} />
                    ) : (
                        record.nodes && <RightOutlined style={{ marginRight: 10 }} onClick={e => onExpand(record, e)} />
                    ) : false)
                }}
                pagination={false}
                tableExtraRender={() => hasPermission([pCodes.dept.add]) && <Button style={{ marginTop: 8 }} key="add" onClick={onAdd} icon={<PlusOutlined />} type="primary">
                    新增部门
                </Button>}
            /> : <YzhSkeleton {...{ rows: 20, style: { padding: 24 } }} />}
            <YzhProgressDialog ref={progressDialogRef} />
            {state.dialogAddVisible ?
                <AddDepartDialog {...state.form}
                    setAddDialog={onSubmit}
                    dialogAddVisible={state.dialogAddVisible} /> : null}
        </Card>
    );
};
export default DepartManage
